package it.cqupt.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(value = "/*")
public class AuthorFilter implements Filter {

        private FilterConfig filterConfig;

        /**
         * 初始化方法，获取过滤器的配置对象
         * @param filterConfig
         * @throws ServletException
         */
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            this.filterConfig = filterConfig;
        }

        @Override
        public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
            //1.定义和协议相关的请求和响应对象
            HttpServletRequest request ;
            HttpServletResponse response;
            try{
                //2.把参数转换成协议相关的对象
                request = (HttpServletRequest)req;
                response = (HttpServletResponse)resp;

                String requestURI = request.getRequestURI();
                requestURI = requestURI.substring(9);
                String queryString = request.getQueryString();
                String url = requestURI;
                if(queryString != null){
                    int index = queryString.indexOf('&');
                    if(index != -1){
                        queryString = queryString.substring(0,index);
                    }
                    url = url+"?"+queryString;
                }
                if(url.endsWith("list")){
                    Object authorStr = request.getSession().getAttribute("authorStr");
                    if(authorStr == null){
                        req.getRequestDispatcher("/unauthorized.jsp").forward(req,resp);
                        return;
                    }
                    String authsor = authorStr.toString();
                    if(authsor.contains(url)){
                        chain.doFilter(request,response);
                        return;
                    }else{
                        req.getRequestDispatcher("/unauthorized.jsp").forward(req,resp);
                        return;
                    }
                }
                //6.放行
                chain.doFilter(request,response);
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        @Override
        public void destroy() {
            //可以做一些清理操作
        }

}
